import axios from "axios";
import router from "@/router";
import { getToken } from "@utils/token";

const request = axios.create({
    baseURL:"http://localhost:8080",
    withCredentials:false,
    timeout:5000
})

request.defaults.headers["Content-Type"] = "application/json;charset=utf-8"
//请求拦截器
request.interceptors.request.use(
    config =>{
        if(getToken("token")){
            config.headers["Authorization"] = getToken("token");
        }
        return config;
    },
    error =>{
        return Promise.reject(error);
    }
)
//响应拦截器
request.interceptors.response.use(
    response=>{
        //对响应数据进行操作
        /*
            Result:
            {
                "code":
                "msg":
                "data":
            }
        */
        let {msg,code} = response.data;
        console.log(msg,code);
        if (code == 200) {
            ElMessage.success(msg);
            return response.data;
        } else if (code == 500) {
            ElMessage.error("服务端异常!!!");
        } else if (code == 406) {
            ElMessage.error(msg);
            return response.data;
        } else if (code == 407) {
            ElMessage.error(msg);
            return response.data;
        }else if (code == 401) {
            ElMessage.error("没有操作权限!!!");
        } else if (code == 403) {
            ElMessage.error("登陆过期!!!");
            //清除pinia、sessionStorage中的数据
            window.sessionStorage.clear();
            router.push('/login');

        }
        return Promise.reject(new Error(msg));

    },
    error=>{
        ElMessage.error("没有操作权限!!!");
        window.sessionStorage.clear();
        router.push("/login");
        return Promise.reject(error);
    }

)

export default request